package com.fw.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fw.entity.Result;
import com.fw.utils.JWTUtils;
import com.fw.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    private boolean OFF = true;//true为关闭jwt令牌验证功能

    /**
     * 返回 false：请求被拦截，返回
     * 返回 true ：请求OK，可以继续执行，放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if(OFF) return true;
        String token = request.getHeader("token");
        token = token.replaceAll("\"", "");
        if(token == null || token.equals("")) {
            returnErrorResponse(response, new Result(null, "您尚未登录", "0111"));
            return false;
        }
        String userid = JWTUtils.getUserId(token);
        String rToken = RedisUtil.get(userid).toString();
        if(token.equals(rToken))return true;
        else if(!token.equals(rToken) && rToken != null && !rToken.equals("")){
            returnErrorResponse(response, new Result(null, "您的账号于异地登录", "0108"));
            return false;
        }
        else {
            returnErrorResponse(response, new Result(null, "您的账号已失效", "0109"));
            return false;
        }
    }

    /**
     * 发送jwt的验证结果到客户端
     * @author LiJun
     * @Date 2019/9/28
     * @Time 15:13
     * @param response
     * @param result
     * @return void
     */
    private void returnErrorResponse(HttpServletResponse response, Result result) throws IOException {
        OutputStream out = null;
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JSONObject.toJSON(result).toString().getBytes("utf-8"));
            out.flush();
        } finally{
            if(out != null){
                out.close();
            }
        }
    }

    /**
     * 请求controller之后，渲染视图之前
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求controller之后，视图渲染之后
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
